/*
 * GameThread.java
 *
 * This work is free software; you can redistribute it and/or
 * modify it under the terms of the Apache License as published 
 * by the Apache Software Foundation.
 *
 * This work is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 * Apache License for more details.
 *
 * Copyright (c) 2011 Tran Hoang Anh (tranhoanganh89@gmail.com). 
 * All rights reserved.
 */
package net.hoanganh.jbraintetris;

/**
 * Thread using for game. It support pausing function and set interval at run
 * time.
 */
public class GameThread extends Thread {

	private static final int PAUSING_TIME_SLEEP = 1000;

	/**
	 * Set when game is paused.
	 */
	private boolean paused = false;

	/**
	 * Game interval in millisecond.
	 */
	private int interval = 0;

	/**
	 * Create new game thread.
	 * 
	 * @param interval
	 *            the interval between each game run
	 */
	public GameThread(int interval) {
		if (interval <= 0) {
			throw new IllegalArgumentException("inteval is positive.");
		}

		this.interval = interval;
	}

	/**
	 * Check if game is paused or not.
	 * 
	 * @return true if game is paused
	 */
	public boolean isPaused() {
		return paused;
	}

	/**
	 * Set game is paused
	 * 
	 * @param paused
	 *            the paused to set
	 */
	public void setPaused(boolean paused) {
		this.paused = paused;
	}

	/**
	 * Get the interval time.
	 * 
	 * @return the interval
	 */
	public int getInterval() {
		return interval;
	}

	/**
	 * Set the interval time.
	 * 
	 * @param interval
	 *            the interval to set
	 */
	public void setInterval(int interval) {
		if (interval <= 0) {
			throw new IllegalArgumentException("inteval is positive.");
		}

		this.interval = interval;
	}

	/**
	 * Run game thread.
	 */
	public void run() {

		while (true) {
			handleTimer();

			try {
				sleep(interval);

				while (paused) {
					sleep(PAUSING_TIME_SLEEP);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * This method will be invoked after specific interval time.
	 */
	protected void handleTimer() {
	}
}
